package com.example.demo5;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*") // 通配符 wildcard 外卡
public class EncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String uri=httpServletRequest.getRequestURI();
        if(uri.equals("admin")){
            int role=-1;
            if(httpServletRequest.getSession().getAttribute("role")!=null){
                role = (int) httpServletRequest.getSession().getAttribute("role");
            }
            if(role!=1){
                httpServletRequest.setAttribute("error","error");
                httpServletRequest.getRequestDispatcher("/index.jsp").forward(request,response);
            }
        } else if (uri.equals("employee")) {
            int role=-1;
            if(httpServletRequest.getSession().getAttribute("role")!=null){
                role= (int) httpServletRequest.getSession().getAttribute("role");
            }
            if (role != 0) {
                httpServletRequest.setAttribute("error","error");
                httpServletRequest.getRequestDispatcher("/index.jsp").forward(request,response);

            }
            }
        chain.doFilter(request, response);
        }


    }

